import { defineStore } from "pinia";
import { ref } from "vue";
import {
  userRegisterService,
  userLoginService,
  getUserInfoService,
  updateUserInfoService,
  updateUserPwdService,
  updateUserAvatar,
} from "@/api/user";
import router from "@/router";

export const useUserStore = defineStore(
  "user",
  () => {
    const token = ref("");
    const isRegist = ref(false);
    const loginForm = ref();
    //登录和注册的表单信息
    const LoginFormData = ref({
      username: "",
      password: "",
      repassword: "",
    });
    //用户信息
    const userInfo = ref({
      id: "",
      username: "",
      nickname: "",
      email: "",
      user_pic: "",
    });
    //默认头像地址
    const baseUrl = ref(
      "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
    );
    const squareUrl = ref(
      "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png"
    );

    //登录注册表单的校验
    const rules = {
      username: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        {
          pattern: /^[a-zA-Z0-9]{1,10}$/,
          message: "用户名必须是1-10位的大小写字母和数字",
          trigger: "blur",
        },
      ],
      password: [
        { required: true, message: "请输入密码", trigger: "blur" },
        {
          pattern: /^\S{6,15}$/,
          message: "密码必须是6-15位的非空字符",
          trigger: "blur",
        },
      ],
      repassword: [
        { required: true, message: "请输入密码", trigger: "blur" },
        {
          pattern: /^\S{6,15}$/,
          message: "密码必须是6-15位的非空字符",
          trigger: "blur",
        },
        {
          validator: (rule, value, callback) => {
            if (value !== LoginFormData.value.password) {
              callback(new Error("两次输入的密码不一致"));
            } else {
              callback();
            }
          },
          trigger: "blur",
        },
      ],
    };
    //处理dropdown的函数
    const handleCommand = (command) => {
      if (command !== "/login") {
        router.push("/user" + command);
      } else {
        //用户退出功能
        ElMessageBox.confirm("你确定要退出登录吗?", "温馨提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            //清除token
            token.value = "";
            //清除用户数据
            userInfo.value = {
              id: "",
              username: "",
              nickname: "",
              email: "",
              user_pic: "",
            };
            //清除登录表单数据
            LoginFormData.value = {
              username: "",
              password: "",
              repassword: "",
            };
            router.push(command);
            ElMessage({
              type: "success",
              message: "已退出",
            });
          })
          .catch(() => {
            ElMessage({
              type: "success",
              message: "取消成功",
            });
          });
      }
    };
    //跳回到登录页
    const goToLogin = () => {
      isRegist.value = false;
      LoginFormData.value = {
        username: "",
        password: "",
        repassword: "",
      };
    };
    //跳回到注册页
    const goToRegist = () => {
      isRegist.value = true;
      LoginFormData.value = {
        username: "",
        password: "",
        repassword: "",
      };
    };
    //用户注册
    const register = async () => {
      await loginForm.value.validate();
      userRegisterService(LoginFormData.value);
      ElMessage.success("注册成功");
      LoginFormData.value = {
        username: "",
        password: "",
        repassword: "",
      };
      isRegist.value = false;
    };
    //用户登录
    const login = async () => {
      await loginForm.value.validate();
      const res1 = await userLoginService(LoginFormData.value);
      ElMessage.success(res1.message);
      token.value = res1.token;
      //获取用户信息
      const res2 = await getUserInfoService();
      userInfo.value = { ...res2.data };
      LoginFormData.value = {
        username: "",
        password: "",
        repassword: "",
      };
      router.push("/");
    };
    //---------------------------------------------------------------------------------
    //绑定用户信息修改的表单
    const infoForm = ref();
    //用户信息修改
    const userInfoForm = ref({
      id: "",
      username: "",
      nickname: "",
      email: "",
      user_pic: "",
    });
    const copyInfo = () => {
      userInfoForm.value = { ...userInfo.value };
    };
    //用户信息的校验
    const userInfoRules = {
      nickname: [
        { required: true, message: "请输入用户昵称", trigger: "blur" },
        {
          pattern: /^\S{1,10}$/,
          message: "用户昵称必须是1-10位非空字符",
          trigger: "blur",
        },
      ],
      email: [
        { required: true, message: "请输入邮箱", trigger: "blur" },
        {
          pattern: /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/,
          message: "您的输入不是一个邮箱",
          trigger: "blur",
        },
      ],
    };

    //用户修改信息的提交
    const changeInfo = async () => {
      await infoForm.value.validate();
      const res = await updateUserInfoService(userInfoForm.value);
      userInfo.value = { ...userInfoForm.value };
      ElMessage.success(res.message);
      router.push("/");
    };
    //---------------------------------------------------------------------------
    //用户密码修改
    const repasswordForm = ref({
      old_pwd: "",
      new_pwd: "",
      re_pwd: "",
    });
    //修改密码表单的校验
    const repasswordRules = {
      old_pwd: [
        { required: true, message: "请输入老密码", trigger: "blur" },
        {
          pattern: /^\S{6,15}$/,
          message: "密码必须是6-15位非空字符",
          trigger: "blur",
        },
      ],
      new_pwd: [
        { required: true, message: "请输入新密码", trigger: "blur" },
        {
          pattern: /^\S{6,15}$/,
          message: "密码必须是6-15位非空字符",
          trigger: "blur",
        },
      ],
      re_pwd: [
        { required: true, message: "请再次输入新密码", trigger: "blur" },
        {
          pattern: /^\S{6,15}$/,
          message: "密码必须是6-15位非空字符",
          trigger: "blur",
        },
        {
          validator: (rule, value, callback) => {
            if (value !== repasswordForm.value.new_pwd) {
              callback(new Error("两次输入的密码不匹配"));
            }
          },
          trigger: "blur",
        },
      ],
    };

    //修改表单元素的清除
    const clear = () => {
      repasswordForm.value = {
        old_pwd: "",
        new_pwd: "",
        re_pwd: "",
      };
    };
    //修改密码的提交
    const changePassword = async () => {
      const res = await updateUserPwdService(repasswordForm.value);
      console.log(res.code);
      if (res.code === 0) {
        ElMessage.success(res.message);
        clear();
        //用户重新登录
        //清除token
        token.value = "";
        //清除用户数据
        userInfo.value = {
          id: "",
          username: "",
          nickname: "",
          email: "",
          user_pic: "",
        };
        //回到登录页
        router.push("/login");
      }
    };

    //修改头像
    const avatarImg = ref();

    const uploadAvatar = (uploadFile) => {
      //基于FileReader读取图片做预览
      const reader = new FileReader();
      reader.readAsDataURL(uploadFile.raw);
      reader.onload = () => {
        avatarImg.value = reader.result;
      };
    };
    //头像上传
    const submit = async () => {
      const res = await updateUserAvatar(avatarImg.value);
      ElMessage.success(res.message);
      //重新渲染
      userInfo.value.user_pic = avatarImg.value;
      router.push("/");
    };
    return {
      token,
      isRegist,
      LoginFormData,
      loginForm,
      infoForm,
      rules,
      baseUrl,
      squareUrl,
      userInfo,
      handleCommand,
      goToLogin,
      goToRegist,
      register,
      login,
      changeInfo,
      copyInfo,
      userInfoRules,
      userInfoForm,
      repasswordForm,
      repasswordRules,
      avatarImg,

      uploadAvatar,
      clear,
      changePassword,
      submit,
    };
  },
  {
    persist: true,
  }
);
